import axios from 'axios';

// import { MessageBox, Message } from 'ElementPlus'
import { ElMessage as Message } from 'element-plus'
import Qs from 'qs'
import { setCookie, getCookie, delCookie } from '@/utils/util'
axios.defaults.withCredentials=true; //允许跨域携带COOKIE

var baseURL;
// const baseURL = (process.env.NODE_ENV !== "development"?'/api':'');
if(process.env.NODE_ENV === "development")
{
     baseURL = '/api/'
}
else
{
     baseURL = '/api/'
}
// console.log(baseURL)
/**
 * 
 * @param {*} url 路径
 * @returns  {string} 新路径  
 */
function changeUrl(url){
    if (process.env.NODE_ENV === "development") {
        // alert("开发环境");
        return url;
      }else {
        console.log(url)
        var ary = url.split('/');
        console.log(ary)
        var new_url='/';
        for(let i=2;i<ary.length;i++)
        {
            new_url=new_url+ary[i]+'/';
            console.log(new_url);
        }
        return '/spare'+new_url;
        // alert("生产环境");
    }
}


// 登录请求方法
const loginreq = (method, url, params) => {
    // console.log(process.env.VUE_APP_BASE_API)
    // console.log(url)
    // url =change(url)    //判断是不是生产环境，截取掉 /api/
    // console.log(url)
    return axios({
        baseURL:baseURL,
        method: method,
        url: url,
        // headers: {
        //     'Content-Type': 'application/x-www-form-urlencoded',
        // },
        data: params,
        // traditional: true,
        // transformRequest: [
        //     function(data) {
        //         let ret = ''
        //         for (let it in data) {
        //             ret +=
        //                 encodeURIComponent(it) +
        //                 '=' +
        //                 encodeURIComponent(data[it]) +
        //                 '&'
        //         }
        //         return ret
        //     }
        // ]
    }).then(res => res.data);
};

const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    // baseURL:'/api/',
    baseURL:baseURL,
    timeout: 500000 // request timeout
})
service.interceptors.request.use(
    config => {
      const token = getCookie('token');
    //   Cookies.set('token',token)
      config.headers['token'] = token;
      if(token)
      {
          console.log(token)
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
)

service.interceptors.response.use(

    response => {
        console.log(response);
        // console.log(response,'response')
      const res = response.data
      let filename;
      if(response.headers["content-disposition"])
      {
        filename =response.headers["filename"]  //取得文件名
      }
      if(filename)
      {
        // console.log(response.data["filename"])
        response.data["filename"]=decodeURI(filename)  
        // console.log(response.data["filename"])
      }
        if(res.code == '401')  //登录认证失败
        {
            Message({
                message: '登录失效',
                type: 'error',
                duration: 5 * 1000
            })
            router.push({ path: '/' })
        }
        else if(res.state!=100)
        {
            Message({
                message: res.message,
                type: 'error',
                duration: 5 * 1000
            })
        }
      return response.data;
    },
    error => {
      console.log('err' + error) // for debug
      Message({
        message: error.message || error.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // return Promise.reject(error)
    }
)

//requestParam 数组
const reqAryQs = (method, url, params) => {
    // console.log(Qs.stringify(params,{arrayFormat: 'repeat'}))
    // url =change(url) 
    return service({
        method: method,
        url: url,
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json',

            // token: localStorage.getItem('logintoken')
        },
        // data: params,
        data:Qs.stringify(params,{arrayFormat: 'repeat'})
    });
}




const req = (method, url, params) => {
    // console.log(Qs.stringify(params,{arrayFormat: 'repeat'}))
    // url =change(url) 
    // console.log(Qs.stringify(params))
    return service({
        method: method,
        url: url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json',

            // token: localStorage.getItem('logintoken')
        },
        // data: params,
        data:Qs.stringify(params)
    });
}

const reqNoQs = (method, url, params) => {
    // url =change(url) 
    // console.log(params,url)
    return service({
        method: method,
        url: url,
        // headers: {
        //     // 'Content-Type': 'application/x-www-form-urlencoded',
        //     // 'Content-Type': 'application/json',

        //     // token: localStorage.getItem('logintoken')
        // },
        data: params,
        // data:Qs.stringify(params)
    });
}

//from-data  文件发送
const reqFM = (method, url, params) => {

    // url =change(url) 
    return service({
        method: method,
        url: url,
        headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json',
            'Content-Type':'multipart/form-data'
            // token: localStorage.getItem('logintoken')
        },
        data: params,
        // data:Qs.stringify(params)
    });
}

//get请求  axios get用parmas  post 用data
const reqGet = (method, url, params) => {

    // url =change(url) 
    return service({
        method: method,
        url: url,
        headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json',
            // headers:{'Content-Type':'multipart/form-data'}
            token: localStorage.getItem('logintoken')
        },
        params: params,
        // data:Qs.stringify(params)
    });
}
const reqGetAryQs = (method, url, params) => {
    // console.log(Qs.stringify(params,{arrayFormat: 'repeat'}))
    // url =change(url) 
    return service({
        method: method,
        url: url,
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json',

            // token: localStorage.getItem('logintoken')
        },
        // data: params,
        params:Qs.stringify(params,{arrayFormat: 'repeat'})
    });
}

const downloadFM = (method, url, params) => {
    // console.log(Qs.stringify(params,{arrayFormat: 'repeat'}))
    // url =change(url) 
    return service({
        method: method,
        url: url,
        responseType:'blob',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json; charset=utf-8',
            withCredentials: true,
        },
        // data: params,
        data:params,
        params:params
    }).then(res=>{
        if(res.type=='application/json')  //返回文件失败时返回的json
        {    
            const reader = new FileReader();
                reader.readAsText(res, 'utf-8');
                reader.onload = () => {
                //处理报错信息 JSON.parse(reader.result)拿到报错信息
                const msg = JSON.parse(reader.result)
                Message({
                    message: msg.msg,
                    type: 'error',
                    duration: 5 * 1000
                })
            };
            return false
        }
        const filename = res.filename;  //设置文件名
        
        const blob = new Blob([res]);  //接收文件
        var href = window.URL.createObjectURL(blob);  //创建文件存放路径

        var a = document.createElement("a");  //创建A标签
        a.href = href;     //设置a标签的路径为文件路径
        a.download = filename;   //设置a标签的下载属性为要下载的文件名
        document.body.appendChild(a);  //将添加到页面上
        a.click();  //点击进行下载
        a.remove()    //移除A标签

        return true
    }).catch(res=>{
        console.log(res)
        return false
    })
}








export {
    loginreq,
    req,
    reqNoQs,
    reqFM,
    reqGet,
    reqAryQs,
    reqGetAryQs,
    downloadFM,
    changeUrl
    
}